package com.kaver.modular.dc.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaver.core.common.constant.state.ConfigStatus;
import com.kaver.core.shiro.ShiroKit;
import com.kaver.core.shiro.ShiroUser;
import com.kaver.core.support.SafeProperties;
import com.kaver.modular.dc.service.IDcConfigService;
import com.kaver.modular.system.dao.DcConfigMapper;
import com.kaver.modular.system.model.DcConfig;

/**
 * <p>
 * 配置项 服务实现类
 * </p>
 *
 * @author Roc
 * @since 2019-01-30
 */
@Service
public class DcConfigServiceImpl extends ServiceImpl<DcConfigMapper, DcConfig> implements IDcConfigService {

	@Override
	public void upload(Integer appId, Integer envId, SafeProperties properties) {
		Set<String> set = properties.propertyNames();
		if (!CollectionUtils.isEmpty(set)) {
			List<DcConfig> entityList = new ArrayList<>();
			ShiroUser user = ShiroKit.getUser();
			set.forEach(key->{
				String value = properties.getProperty(key);
				String comment = properties.getComment(key);
				DcConfig entity = new DcConfig();
				entity.setAppId(appId);
				entity.setEnvId(envId);
				entity.setConfigKey(key);
				Wrapper<DcConfig> wrapper = new EntityWrapper<>(entity);
				DcConfig config = this.selectOne(wrapper);
				if (config == null) {
					DcConfig dcConfig = new DcConfig();
					dcConfig.setAppId(appId);
					dcConfig.setConfigDesc(comment);
					dcConfig.setConfigKey(key);
					dcConfig.setConfigValue(value);
					dcConfig.setCreateTime(new Date());
					dcConfig.setCreateUser(user.getName());
					dcConfig.setEnvId(envId);
					dcConfig.setSensitive(0);
					dcConfig.setStatus(ConfigStatus.NEW.getCode());
					entityList.add(dcConfig);
				}else {
					if (config.getConfigKey().equals(key) && config.getConfigValue().equals(value)&& config.getConfigDesc().equals(comment)) {
						// continue
					} else {
						config.setConfigValue(value);
						config.setConfigDesc(comment);
						config.setUpdateTime(new Date());
						config.setUpdateUser(user.getName());
						if (!config.getStatus().equals(ConfigStatus.NEW.getCode())) {
							config.setStatus(ConfigStatus.UPD.getCode());
						}
						this.updateById(config);
					}
				}
			});
			if (!entityList.isEmpty()) {
				this.insertBatch(entityList);
			}
		}
	}

}
